package com.mobile.util;
import com.alibaba.fastjson.JSON;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ImageCompressionUtils {

    /**
     * 压缩图片并返回 Base64 编码的字符串（JPEG 格式）
     *
     * @param file      MultipartFile 图片文件
     * @param quality   压缩质量 [0.0f - 1.0f]，1 表示原质量
     * @return Base64 编码的图片字符串（不含前缀）
     */
    public static String compressImageToBase64(MultipartFile file, float quality) throws Exception {
        // 将 MultipartFile 转换为 BufferedImage
        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(file.getBytes()));

        // 设置目标图像大小（比如最大 800x800）
        int targetWidth = Math.min(originalImage.getWidth(), 200);
        int targetHeight = Math.min(originalImage.getHeight(), 200);

        // 缩放图片
        Image scaledImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);

        // 创建新的 BufferedImage
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(scaledImage, 0, 0, null);
        g.dispose();

        // 写出到 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(resizedImage, "jpg", outputStream); // 使用 JPEG 格式压缩

        // 转换为 Base64
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        return "data:image/jpeg;base64,"+ base64Image;
    }
    public static MultipartFile convert(File file) throws IOException {
        FileInputStream input = new FileInputStream(file);
        return new MockMultipartFile("file", // 表单中的字段名（可任意）
                file.getName(), // 原始文件名
                "image/jpeg", // 文件类型（根据实际修改）
                input); // 文件内容输入流
    }

    /**
     * 将PPT文件转换为图片文件列表
     * @param pptFile PPT文件
     * @param dpi 图片DPI
     * @return 图片文件路径列表
     */
    public static java.util.List<Path> convertPptToImageFiles(InputStream is, int dpi,String pptPath) throws Exception {
        java.util.List<Path> imageFiles = new ArrayList<>();

        try (SlideShow<?, ?> slideShow = SlideShowFactory.create(is)) {

            Dimension pageSize = slideShow.getPageSize();
            double zoom = dpi / 72.0; // 72是标准DPI

            // 创建图片输出目录（使用原PPT文件所在目录的images子文件夹）
            Path outputDir = Paths.get(pptPath, "images");
            Files.createDirectories(outputDir);

            int slideIndex = 0;
            for (org.apache.poi.sl.usermodel.Slide slide : slideShow.getSlides()) {
                slideIndex++;

                // 创建高分辨率图像
                BufferedImage img = new BufferedImage(
                        (int) (pageSize.width * zoom),
                        (int) (pageSize.height * zoom),
                        BufferedImage.TYPE_INT_RGB
                );

                Graphics2D graphics = img.createGraphics();

                // 设置高质量渲染参数
                setRenderingHints(graphics);

                // 缩放并绘制幻灯片
                graphics.scale(zoom, zoom);
                graphics.setPaint(Color.WHITE);
                graphics.fill(new Rectangle2D.Float(0, 0, pageSize.width, pageSize.height));
                slide.draw(graphics);

                // 保存为PNG文件
                Path imagePath = outputDir.resolve(String.format("slide_%03d.png", slideIndex));
                ImageIO.write(img, "png", imagePath.toFile());
                imageFiles.add(imagePath);

                graphics.dispose();
            }
        }

        return imageFiles;
    }

    /**
     * 设置高质量渲染参数
     */
     static void setRenderingHints(Graphics2D graphics) {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    }

    /**
     * 将图片文件列表转换为Base64响应对象
     */
    public static String convertToBase64Response(java.util.List<Path> imageFiles) throws IOException {
        List<String> base64Images = new ArrayList<>();

        for (Path imagePath : imageFiles) {
            byte[] imageBytes = Files.readAllBytes(imagePath);
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            base64Images.add("data:image/png;base64," + base64Image);
        }

        return JSON.toJSONString(base64Images);
    }

    /**
     * 创建包含所有图片的ZIP文件
     */
    public static byte[] createZipFile(java.util.List<Path> imageFiles) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            for (Path imagePath : imageFiles) {
                ZipEntry entry = new ZipEntry(imagePath.getFileName().toString());
                zos.putNextEntry(entry);
                Files.copy(imagePath, zos);
                zos.closeEntry();
            }
        }
        return baos.toByteArray();
    }

    /**
     * Base64响应对象
     */
    public static class Base64Response {
        private int totalSlides;
        private java.util.List<String> images = new ArrayList<>();

        public int getTotalSlides() {
            return totalSlides;
        }

        public void setTotalSlides(int totalSlides) {
            this.totalSlides = totalSlides;
        }

        public java.util.List<String> getImages() {
            return images;
        }

        public void setImages(List<String> images) {
            this.images = images;
        }

        public void addImage(String image) {
            this.images.add(image);
        }
    }



    /**
     * 将Base64字符串写入本地文本文件
     * @param base64 待写入的Base64字符串
     * @param filePath 目标文件路径（含文件名）
     * @throws IOException 文件操作失败时抛出
     */
    public static void writeBase64ToFile(String base64, String filePath) throws IOException {
        // 检查并创建目录
        createParentDirs(filePath);
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(filePath),
                        StandardCharsets.UTF_8))) {
            writer.write(base64);
        }
    }

    /**
     * 从本地文本文件读取Base64字符串
     * @param filePath 源文件路径（含文件名）
     * @return 读取的Base64字符串
     * @throws IOException 文件操作失败时抛出
     */
    public static String readBase64FromFile(String filePath) throws IOException {
        // 检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("指定的文件不存在: " + filePath);
        }
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(filePath),
                        StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }
        return content.toString();
    }
    // 使用示例
    public static void main(String[] args) {
        String base64Data = "..."; // 示例Base64
        String filePath = "/Users/wbr/uploads/base64.txt"; // 示例路径

        try {
            // 写入文件
            writeBase64ToFile(base64Data, filePath);
            System.out.println("Base64数据已写入文件");

            // 读取文件
            String readData = readBase64FromFile(filePath);
            System.out.println("从文件读取的Base64长度: " + readData.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 检查并创建文件的父目录
     * @param filePath 文件路径
     * @throws IOException 创建目录失败时抛出
     */
    private static void createParentDirs(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        Path parentDir = path.getParent();

        if (parentDir != null && !Files.exists(parentDir)) {
            try {
                Files.createDirectories(parentDir);
            } catch (Exception e) {
                throw new IOException("无法创建目录: " + parentDir, e);
            }
        }
    }
}